//
//  ViewController.m
//  association
//
//  Created by hibo on 2018/6/28.
//  Copyright © 2018年 hibo. All rights reserved.
//

#import "ViewController.h"
#import <objc/runtime.h>
#import "UIButton+Property.h"
@interface ViewController ()
@end
const NSString *array_key = @"array_association_key";
const NSString *button_click_key = @"button_click_key";
@implementation ViewController
{
    UIButton *clickBtn;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    /*
     _cmd 表示当前方法的selector的一个指针
     */
    NSString *selector = NSStringFromSelector(_cmd);
    NSLog(@"%@",selector);
    
    /*
     objc_setAssociatedObject(id _Nonnull object, const void * _Nonnull key,
     id _Nullable value, objc_AssociationPolicy policy)
     object 关联对象
     key 关联对象的关键字 必须是唯一不可变的常量
     value 被关联者要关联到object上
     policy 关联策略
     示例 给一个数组动态关联一个属性
     */
    NSArray *array = @[@"1",@"2",@"3"];
    NSDictionary *dic = @{@"key":@"value"};
    objc_setAssociatedObject(array, &array_key, dic, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    NSDictionary *di = objc_getAssociatedObject(array, &array_key);
    NSLog(@"%@",array);
    NSLog(@"%@",di);
    
    //断开关联
    objc_setAssociatedObject(array, &array_key, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    di = objc_getAssociatedObject(array, &array_key);
    NSLog(@"断开关联后的对象：%@",di);
    //断开所有关联
    objc_removeAssociatedObjects(array);
    
    
    //关联一个方法，点击事件代码块回调
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake((self.view.frame.size.width-100)/2, 200, 100, 40)];
    button.backgroundColor = [UIColor redColor];
    button.ids = @"hibo";
    [button setTitle:@"点击" forState:UIControlStateNormal];
    [self.view addSubview:button];
    button.clickBlock = ^(UIButton *response) {
        NSLog(@"代码块实现点击事件回调：%@",response.titleLabel.text);
    };
}

@end

